package com.tvunetworks.center.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tvunetworks.center.common.constant.LocalConstant;
import com.tvunetworks.center.common.exception.ServerException;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.common.model.UserBehavior;
import com.tvunetworks.center.common.util.JsonUtil;
import com.tvunetworks.center.common.util.MyUtil;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.gs.model.Device;
import com.tvunetworks.center.user.mapper.BookmarkDeviceMapper;
import com.tvunetworks.center.user.mapper.UserBehaviorMapper;
import com.tvunetworks.center.user.mapper.UserBookmarkMapper;
import com.tvunetworks.center.user.mapper.UserMapper;
import com.tvunetworks.center.user.model.BookmarkDevice;
import com.tvunetworks.center.user.model.UserBookmark;
import com.tvunetworks.center.user.model.json.Device4MultiView;
import com.tvunetworks.center.user.model.param.PageParam;
import com.tvunetworks.center.user.model.param.ProcessUserOprationParam;
import com.tvunetworks.center.user.model.param.UserLogRecordPo;
import com.tvunetworks.center.user.model.param.UserOperationParam;
import com.tvunetworks.center.user.model.result.ResultConstant;
import com.tvunetworks.center.user.model.vo.PageUserVo;
import com.tvunetworks.center.user.service.DeviceService;
import com.tvunetworks.center.user.service.UserBehaviorService;
import com.tvunetworks.center.user.service.feign.DeviceFeignService;
import com.tvunetworks.center.user.util.JwtUtil;
import com.tvunetworks.center.user.util.RedisUtil;
import com.tvunetworks.center.user.util.UserThreadPool;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: tvucc-aggregator
 * @description: UserBehaviorImpl
 * @author lebronchen
 * @create: 2019-03-28 09:43
 **/
@Service
@Slf4j
public class UserBehaviorServiceImpl implements UserBehaviorService {

    @Autowired
    private UserBehaviorMapper userBehaviorMapper;


    @Value("${redis.key.userBehavior}")
    private String userBehaviorKey;


    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private DeviceFeignService deviceFeignService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private BookmarkDeviceMapper bookmarkDeviceMapper;
    @Autowired
    private UserBookmarkMapper userBookmarkMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserMapper userMapper;
    @Value("${server.name}")
    private String serverName;
    @Value("${process.url}")
    private String processUrl;
    @Value("${uniformJWTKet}")
    private String uniformJWTKet;
    @Override
    @Transactional
    public void setUserBehavior(UserBehavior userBehavior) {

        if (userBehavior == null) {
            log.error("Set user behavior error, userBehavior is null");
            return;
        }

        if (StringUtils.isBlank(userBehavior.getUserId())
                || StringUtils.isBlank(userBehavior.getPn())
                || StringUtils.isBlank(userBehavior.getRemark())
                || StringUtils.isBlank(userBehavior.getServerName())
                || StringUtils.isBlank(userBehavior.getContent())) {

            try {
                log.error("Set user behavior error,some userBehavior properties are null {}", JsonUtil.toJsonStr(userBehavior));
            } catch (IOException e) {
                log.error("Set user behavior error,some userBehavior properties are null");
            }

        }
        UserThreadPool.SERVICETHREADPOOL.submit(new Runnable() {
            @Override
            public void run() {
                String key = String.join(":", userBehaviorKey, userBehavior.getServerName(),
                        userBehavior.getUserId(), userBehavior.getPn(), userBehavior.getRemark());

                //Save 1 day
                redisUtil.set(key, userBehavior.getContent(), 86400L);

                UserBehavior exist = null;

                try {
                    exist = getUniqueUserBehavior(userBehavior.getUserId(), userBehavior.getPn(), userBehavior.getRemark());
                } catch (Exception e) {
                    log.error(e.toString(), e);
                    return;
                }

                if (exist == null) {
                    userBehavior.setId(MyUtil.getUUID());
                    userBehavior.setUpdateTime(String.valueOf(System.currentTimeMillis()));
                    userBehaviorMapper.insert(userBehavior);
                } else {
                    exist.setPeerId(userBehavior.getPeerId());
                    exist.setContent(userBehavior.getContent());
                    exist.setUpdateTime(String.valueOf(System.currentTimeMillis()));
                    userBehaviorMapper.updateByPrimaryKeySelective(exist);
                }

            }
        });
      /*  UserThreadPool.SERVICETHREADPOOL.submit(new Thread(() -> {

            String key = String.join(":", userBehaviorKey, userBehavior.getServerName(),
                    userBehavior.getUserId(), userBehavior.getPn(), userBehavior.getRemark());

            //Save 1 day
            redisUtil.set(key, userBehavior.getContent(), 86400L);

            UserBehavior exist = null;

            try {
                exist = getUniqueUserBehavior(userBehavior.getUserId(), userBehavior.getPn(), userBehavior.getRemark());
            } catch (Exception e) {
                log.error(e.toString(), e);
                return;
            }

            if (exist == null) {
                userBehavior.setId(MyUtil.getUUID());
                userBehavior.setUpdateTime(String.valueOf(System.currentTimeMillis()));
                userBehaviorMapper.insert(userBehavior);
            } else {
                exist.setPeerId(userBehavior.getPeerId());
                exist.setContent(userBehavior.getContent());
                exist.setUpdateTime(String.valueOf(System.currentTimeMillis()));
                userBehaviorMapper.updateByPrimaryKeySelective(exist);
            }
        }));
*/
    }

    @Override
    public Result<String> getUserBehavior(UserBehavior userBehavior) {

        String key = String.join(":", userBehaviorKey, userBehavior.getServerName(),
                userBehavior.getUserId(), userBehavior.getPn(), userBehavior.getRemark());

        String behaviorResult = (String) redisUtil.get(key);

        if (StringUtils.isNotBlank(behaviorResult)) {
            return ResultUtil.success(behaviorResult);
        }

        UserBehavior exist = null;
        try {
            exist = getUniqueUserBehavior(userBehavior.getUserId(), userBehavior.getPn(), userBehavior.getRemark());
        } catch (Exception e) {
            log.error("Get User behavior from db exception", e);
            return ResultUtil.error("81000302", "Not unique user behavior");
        }
        if (exist == null) {
            return ResultUtil.success();
        }

        //Save 1 day
        redisUtil.set(key, userBehavior.getContent(), 86400L);
        return ResultUtil.success(exist.getContent());
    }

    @Override
    public Result<Map<String, String>> getUserBehaviors(UserBehavior userBehavior) {

        if (StringUtils.isBlank(userBehavior.getUserId()) || StringUtils.isBlank(userBehavior.getPn())
                || StringUtils.isBlank(userBehavior.getRemark()) || StringUtils.isBlank(userBehavior.getServerName())) {
            return ResultUtil.error("81000301", "Pn and remark and serverName can not be null");
        }

        List<String> remarks = Arrays.asList(userBehavior.getRemark().split(","));

        Map<String, String> result = new HashMap<>();

        UserBehavior tempUserBehavior = new UserBehavior();

        for (String remark : remarks) {
            tempUserBehavior.setServerName(userBehavior.getServerName())
                    .setRemark(remark)
                    .setPn(userBehavior.getPn())
                    .setUserId(userBehavior.getUserId());

            Result<String> singleResult = getUserBehavior(tempUserBehavior);

            if (ResultUtil.SUCCESS.equals(singleResult.getErrorCode())) {
                result.put(remark, singleResult.getResult());
            } else {
                log.error("Get user behavior remark {} error  {} ", remark, singleResult.getErrorInfo());
                result.put(remark, null);
            }
        }

        return ResultUtil.success(result);
    }

    private UserBehavior getUniqueUserBehavior(String userId, String pn, String remark) {
        UserBehavior userBehavior = new UserBehavior();
        userBehavior.setUserId(userId);
        userBehavior.setPn(pn);
        userBehavior.setRemark(remark);
        // 正常情况下只会有一条记录但是，由于是多线程 insert 可能导致多条数据
        List<UserBehavior> select = userBehaviorMapper.select(userBehavior);


        // 没有查到结果
        if (CollectionUtils.isEmpty(select)) {
            return null;
        }

        // 只查到一个结果
        if (select.size() == 1) {
            return select.get(0);
        }


        //select.size() > 1, 查到多个结果只取最后一个并删除其它的
        for (int i = 0; i < select.size() - 1; i++) {
            UserBehavior needDelBehavior = select.get(i);
            log.error("delete user behavior [{}] : [{}] : [{}]", needDelBehavior.getUserId(), needDelBehavior.getPn(), needDelBehavior.getRemark());
            // 如果有多条数据则进行删除
            userBehaviorMapper.deleteByPrimaryKey(select.get(i));
        }

        return select.get(select.size() - 1);


    }

    @Override
    public UserBehavior userBehavior(String userId, String pn) throws Exception {
        UserBehavior userBehavior = new UserBehavior();
        userBehavior.setUserId(userId);
        userBehavior.setPn(pn);
        return userBehaviorMapper.selectOne(userBehavior);
    }

    @Override
    public void updataUserBehavior(UserBehavior userBehavior) throws Exception {
        UserBehavior userB = this.userBehavior(userBehavior.getUserId(), userBehavior.getPn());
        if (userB == null) {
            userBehavior.setId(MyUtil.getUUID());
            userBehaviorMapper.insert(userBehavior);
        } else {
            userBehavior.setId(userB.getId());
            userBehaviorMapper.updateByPrimaryKeySelective(userBehavior);
        }
    }

    @Override
    public UserBehavior queryUserBehavior(UserBehavior userBehavior) throws Exception {
        return userBehaviorMapper.selectOne(userBehavior);
    }

    /**
     *
     * @param userId userId
     * @param pn pn
     * @param sort 排序规则
     * @return Map
     * @throws Exception 编译异常
     */
    public Map queryUserBehaviorList(String userId, String pn,String sort) throws Exception {
        Map resultMap = new HashMap();
        UserBehavior temp = new UserBehavior();
        temp.setPn(pn);
        temp.setUserId(userId);
        List<UserBehavior> userBehaviorList = userBehaviorMapper.select(temp);
    //    List<UserBehavior> userBehaviorList = new ArrayList<>();
     //   log.error("print the userBehavior  message :[{}] ",userBehaviorLists );
       /* userBehaviorLists.forEach(
                s -> {
                    if ( StringUtils.isNotEmpty(s.getPeerId()) && deviceFeignService.getCurrentDevice(s.getPeerId())!=null) {
                        if (StringUtils.contains(status, deviceFeignService.getCurrentDevice(s.getPeerId()).getStatus())) {
                            userBehaviorList.add(s);
                        }
                    }
                }
        );*/


        if (CollectionUtils.isEmpty(userBehaviorList)) {
            UserBehavior temps = new UserBehavior();
            temps.setPn("mv");
            temps.setUserId(userId);
            List<UserBehavior> select = userBehaviorMapper.select(temps);
            for (UserBehavior userBehavior : select) {
                if (StringUtils.equals("splitScreen", userBehavior.getRemark())) {
                    // 1.page split screen
                    String splitScreen = userBehavior.getContent();
                    resultMap.put("splitScreenNum",splitScreen);
                }
            }
        }

        // classification user behavior 1.splitScreen 2.receiver 3.cloud
        if (userBehaviorList != null && userBehaviorList.size() > 0) {
            List<Map<String, String>> rList = new ArrayList<Map<String, String>>();
      //      List<Map<String, String>> cList = new ArrayList<Map<String, String>>();
            List<String> userBindPeerIdList = deviceFeignService.getBindTRPeerIdList(userId);
//            log.error("===userBehaviorForMv,userBehaviorList:"+JSONObject.toJSONString(userBehaviorList));
//            log.error("===userBehaviorForMv,userBindPeerIdList:"+JSONObject.toJSONString(userBindPeerIdList));
            String splitScreen = "";
            String showInfo = "";

            try {
                for (UserBehavior ub : userBehaviorList) {
                    if (StringUtils.equals("splitScreen", ub.getRemark())) {
                        // 1.page split screen
                        splitScreen = ub.getContent();
                    }else if ("voip".equals(ub.getRemark())) {
                            JSONObject jo = JSONObject.parseObject(ub.getContent());
                            // set http or https request according to user behavior
                            String  voipFlag = jo.getString("mvIsHttpsPage");
                        resultMap.put("voipFlag",voipFlag);
                    }else if("showInfo".equals(ub.getRemark())){
                        showInfo = ub.getContent();
                        resultMap.put("showInfo", showInfo);
                    }else  {
                        JSONObject jsonObject = JSONObject.parseObject(ub.getContent());
                        if (StringUtils.equals("receiver", ub.getRemark()) &&jsonObject !=null ) {
                            // 2.receiver
                            Map<String, String> map = new HashMap<String, String>();
                            String peerId = jsonObject.getString("peerId");
                            if (userBindPeerIdList.contains(peerId)) {
                                // R in user
                                map.put("bookmarkId", jsonObject.getString("bookmarkId"));
                                map.put("peerId", peerId);
                                map.put("userBehaviorUpdateTime",ub.getUpdateTime());
                                rList.add(map);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                throw new ServerException(ResultConstant.UserBehavior.PARSING_BEHAVIOR);
            }
//            log.error("===userBehaviorForMv,rList:"+JSONObject.toJSONString(userBehaviorList));
            // receiver
            List<Device4MultiView> receiverList = new ArrayList<>();
            List<Device4MultiView> receiverListOrderLive = new ArrayList<Device4MultiView>();
            List<Device4MultiView> receiverListOrderOnline = new ArrayList<Device4MultiView>();
            List<Device4MultiView> receiverListOrderOfLine = new ArrayList<Device4MultiView>();

            if (rList != null && rList.size() > 0) {

                for (Map<String, String> map : rList) {

                    Device4MultiView device4MultiView = this.takeReceiverDevice4MultiView(map.get("bookmarkId"), map.get("peerId"), userId, true,map.get("userBehaviorUpdateTime"));
                    log.error("===userBehaviorForMv,device4MultiView ==peerId=:"+map.get("peerId")+"==device4MultiView:"+JSONObject.toJSONString(device4MultiView));
                    if (device4MultiView != null) {
                        if("2".equals(device4MultiView.getStatus())){
                            receiverListOrderLive.add(device4MultiView);
                        }else if("1".equals(device4MultiView.getStatus())){
                            receiverListOrderOnline.add(device4MultiView);
                        }else {
                            receiverListOrderOfLine.add(device4MultiView);
                        }
                    }
                }
            }
            if(receiverListOrderLive.size()>0){
                receiverList.addAll(receiverListOrderLive);
            }
            if(receiverListOrderOnline.size()>0){
                receiverList.addAll(receiverListOrderOnline);
            }
            if(receiverListOrderOfLine.size()>0){
                receiverList.addAll(receiverListOrderOfLine);
            }
//            log.error("===userBehaviorForMv, receiverList:"+JSONObject.toJSONString(receiverList));
            // init data to page
            resultMap.put("splitScreenNum",splitScreen);

            if ( CollectionUtils.isEmpty(receiverList)) {
                resultMap.put("device4MultiView","");
            }else {
                //或者按照名字排序
                if (StringUtils.equals("Name",sort)){
                    receiverList = receiverList.stream().sorted(Comparator.comparing(s->s.getName())).collect(Collectors.toList());

                }

                //也可以按照设备状态排序
                if (StringUtils.equals("Status",sort)){
                    // 倒序，并且如果 status 为 null 则排到最后
                    receiverList = receiverList.stream()
                            .sorted(Comparator.comparing(Device4MultiView::getStatus).reversed().thenComparing(Device4MultiView::getName))
                            .collect(Collectors.toList());
                }
                //默认按照选择顺序,也就是时间排序
                if (StringUtils.equals("Time",sort)){
                    receiverList = receiverList.stream()
                            .sorted(Comparator.comparing(Device4MultiView::getUserBehaviorUpdateTime))
                            .collect(Collectors.toList());
                }


                resultMap.put("device4MultiView",receiverList);
            }

        }
//        log.error("===userBehaviorForMv,resultMap:"+JSONObject.toJSONString(resultMap));

        return resultMap;
    }

    @Override
    public void setRSourceListToRedis(String rid, String sourceTypeList) {
        String key = "source_type_list_"+rid;
        redisUtil.set(key,sourceTypeList,60L);
    }

    @Override
    public String getRSourceListToRedis(String rid) {
        String key = "source_type_list_"+rid;
       return (String)redisUtil.get(key);
    }

    private String urlEncoder(String url) throws UnsupportedEncodingException {
        return URLEncoder.encode(url, "UTF-8");
    }

    /**
     *
     * @param bookmarkId bookmarkId
     * @param peerId peerId
     * @param userId  userId
     * @param fromR fromR
     * @param userBehaviorUpdateTime 用户行为更新时间
     * @return Device4MultiView
     * @throws Exception 编译异常
     */
    public Device4MultiView takeReceiverDevice4MultiView(String bookmarkId,String peerId, String userId, boolean fromR,String userBehaviorUpdateTime) throws Exception{
        Device4MultiView device4MultiView = new Device4MultiView();
        device4MultiView.setPeerId(peerId);
        device4MultiView.setUserBehaviorUpdateTime(userBehaviorUpdateTime);
        Device device = deviceService.getCurrentDevice(peerId);
        log.error("===userBehaviorForMv,device ==peerId:"+peerId+"=bookmarkId:"+bookmarkId+"===device:"+JSONObject.toJSONString(device));
        if ( device != null ) {
            //get live url
            // todo 此处需要从wensocket 去更新
            device4MultiView.setStatus(device.getStatus());
//            Map<String, String> rvfPackMap = new HashMap<String, String>();
//            if ( !fromR ) {
////		        rvfPackMap = getLiveUrlFromMemcache(peerId);
//                rvfPackMap = getLiveUrlFromR(peerId);
//            } else {
//                rvfPackMap = getLiveUrlFromR(peerId);
//            }
//            if ( rvfPackMap != null ) {
//                device4MultiView.setRvfPackOn(Boolean.parseBoolean(rvfPackMap.get("rvfPackOn")));
//                device4MultiView.setLiveUrl(rvfPackMap.get("url"));
//            }

            device4MultiView.setRvfPackOn(false);
            device4MultiView.setLiveUrl("null");

            device4MultiView.setName(device.getName());
            device4MultiView.setIp(device.getIp());
            device4MultiView.setVersion(device.getVersion());
            //on live R set live source info
            if( device.getLivePeerId() != null && StringUtils.isNotBlank(device.getLivePeerId()) ){
                Device liveDevice = deviceService.getCurrentDevice(device.getLivePeerId());
                device4MultiView.setLivePeerId(device.getLivePeerId());
                if( liveDevice != null ){
                    device4MultiView.setPlatform(liveDevice.getPlatform());
                    device4MultiView.setLivePeerName(liveDevice.getName());
                    device4MultiView.setLiveSourceType(liveDevice.getType());
                    device4MultiView.setLiveSourceVersion(liveDevice.getVersion());
                }
            }
            //set bookmark info
            if( StringUtils.isNotBlank(bookmarkId) ){
                UserBookmark bookmark = userBookmarkMapper.queryUserBookmarkById(bookmarkId);
                BookmarkDevice bookmarkDevice = new BookmarkDevice();
                bookmarkDevice.setBookmarkId(bookmarkId);
                bookmarkDevice.setPeerId(peerId);
                BookmarkDevice bd = bookmarkDeviceMapper.selectOne(bookmarkDevice);
                if( bd != null ){
                    //set bookmarkId bookmarkName
                    device4MultiView.setBookmarkId(bookmarkId);
                    device4MultiView.setBookmarkName(bookmark.getBookmarkName());
                }else{
                    //receiver remove from bookmark
                    UserBehavior behavior = new UserBehavior();
                    behavior.setPeerId(peerId);
                    behavior.setPn("mv");
                    behavior.setUserId(userId);
                    List<UserBehavior> temp = deviceFeignService.queryUserBehaviorByExample(behavior);//这个方法查询有问题，和条件不匹配，原因被调用没交@RequestBody  造成参数都被清空
                    log.error("===userBehaviorForMv,queryUserBehaviorByExample size==peerId:"+peerId+"==temp:"+JSONObject.toJSONString(temp));
                    if( !CollectionUtils.isEmpty(temp)){
//                        log.error("===userBehaviorForMv,queryUserBehaviorByExample size=="+JSONObject.toJSONString(temp));
                        //1.remove userbehavior
                        userBehaviorMapper.delete(temp.get(0));
                    }
                    return null;
                }
            }else{
                //处理未被分类的R已经被分配到其他书签下时，不显示用户行文记录
                List<UserBookmark> userBookmarks = userBookmarkMapper.listByUserIdAndPeerId(userId, peerId);
                log.error("===userBehaviorForMv,bookmarkDeviceMapper ==peerId:"+peerId+"==temp:"+JSONObject.toJSONString(userBookmarks));
                if (!CollectionUtils.isEmpty(userBookmarks)) {//如果书签已被迁移需要更新用户行为记录对应的bookmark
                    UserBookmark userBookmark = userBookmarks.get(0);
                    updateUserBehavior(userId, peerId, userBookmark.getId());
                    //set bookmarkId bookmarkName
                    device4MultiView.setBookmarkId(userBookmark.getId());
                    device4MultiView.setBookmarkName(userBookmark.getBookmarkName());
                }
            }
        }
        return device4MultiView;
    }

    /**
     *
     * @param userId userId
     * @param peerId peerId
     * @param bookMarkId bookMarkId
     */
    public void updateUserBehavior(String userId,String peerId,String bookMarkId){
        String content="{\"peerId\":\""+peerId+"\",\"bookmarkId\":\""+bookMarkId+"\"}";
        UserBehavior userBehavior= new UserBehavior();
        userBehavior.setPn("mv");
        userBehavior.setUserId(userId);
        userBehavior.setPeerId(peerId);
        userBehavior.setRemark("receiver");
        userBehavior.setContent(content);
        userBehavior.setUpdateTime(System.currentTimeMillis()+"");
        deviceFeignService.updateUserBehaviorForMv(userBehavior);
    }

    /**
     *
     * @param userBehavior userBehavior
     * @return List
     */
    public List<UserBehavior> userBehaviorList(UserBehavior userBehavior){
        return userBehaviorMapper.select(userBehavior);
    }

    @Override
    public Result<String> listUserOperation(UserOperationParam userOperationParam, LoginUser user) throws Exception{
        ProcessUserOprationParam processUserOprationParam = new ProcessUserOprationParam();

        //set pageParam
        PageParam pageParam = new PageParam();
        pageParam.setPageNum(userOperationParam.getPageNum());
        pageParam.setPageSize(userOperationParam.getPageSize());
        processUserOprationParam.setPageParam(pageParam);
        //set userLogRecordPo
        UserLogRecordPo userLogRecordPo = new UserLogRecordPo();
        userLogRecordPo.setServerName(serverName);
        if(StringUtils.isNotEmpty(userOperationParam.getIp())){
            userLogRecordPo.setIp(userOperationParam.getIp());
        }
        if(StringUtils.isNotEmpty(userOperationParam.getStartTime())){
            userLogRecordPo.setStartTime(userOperationParam.getStartTime());
        }
        if(StringUtils.isNotEmpty(userOperationParam.getEndTime())){
            userLogRecordPo.setEndTime(userOperationParam.getEndTime());
        }
        if(StringUtils.isNotEmpty(userOperationParam.getRequestUrl())){
            userLogRecordPo.setRequestUrl(userOperationParam.getRequestUrl());
        }
        if(StringUtils.isNotEmpty(userOperationParam.getParams())){
            userLogRecordPo.setParams(userOperationParam.getParams());
        }
        if(StringUtils.isNotEmpty(userOperationParam.getUserAgent())){
            userLogRecordPo.setUserAgent(userOperationParam.getUserAgent());
        }
        if(StringUtils.isNotEmpty(userOperationParam.getEmail())){
            userLogRecordPo.setEmail(userOperationParam.getEmail());
        }
        if(LocalConstant.UserRole.SUPPORT.equals(user.getRole()) && StringUtils.isEmpty(userOperationParam.getEmail())){//support 查询所有email
            userLogRecordPo.setEmail("");//传空表示查所有
        }
        if(LocalConstant.UserRole.ADMIN.equals(user.getRole())){//admin,
            if(StringUtils.isEmpty(userOperationParam.getEmail())){
                //查询条件为空，则查询admin 及用户下所有的email
                userLogRecordPo.setEmail(getAllAdminUserEmail(user));
            }else{
                //查询条件不为空则需要查询admin 及用户下所有的email 取交集 查询
                userLogRecordPo.setEmail(getAllAdminUserEmailWithCondition(user,userOperationParam.getEmail()));
            }
        }
        if(LocalConstant.UserRole.USER.equals(user.getRole())){//user,只能查自己的email
            userLogRecordPo.setEmail(user.getEmail());
        }
        processUserOprationParam.setUserLogRecordPo(userLogRecordPo);

        return getOperationFromProcesslog(processUserOprationParam);
    }

    @Override
    public Result<String> listUserEmail(UserOperationParam userOperationParam,LoginUser user) throws Exception {
        List<String> listUserEmail = new ArrayList<>();
        if(user.getEmail().contains(userOperationParam.getEmail())){
            listUserEmail.add(user.getEmail());
        }
        if(LocalConstant.UserRole.SUPPORT.equals(user.getRole())){//support 查询所有email
            listUserEmail = userMapper.listUserEmail(userOperationParam.getEmail());
        }
        if(LocalConstant.UserRole.ADMIN.equals(user.getRole())){//admin,
            List<PageUserVo> listUser = userMapper.adminListUser(user.getId(), userOperationParam.getEmail());
            for (PageUserVo userVo:listUser) {
                listUserEmail.add(userVo.getEmail());
            }
        }
        return ResultUtil.success(listUserEmail);
    }

    /**
     *
     * @param processUserOprationParam processUserOprationParam
     * @return Result
     */
    public Result<String> getOperationFromProcesslog(ProcessUserOprationParam processUserOprationParam){
        String result=null;
        try {
            //调用process log 接口
//            String url = "http://10.12.22.51:2120/tvuuas/uniformApi/v3.0/cc/selectUserOperation";
            long timestamp = System.currentTimeMillis();
            String requestKey = JwtUtil.MD5(timestamp + uniformJWTKet);
            //param
            Map<String,Object> map = new HashMap<>();
            map.put("userLogRecordPo",processUserOprationParam.getUserLogRecordPo());
            map.put("pageParam",processUserOprationParam.getPageParam());
            String paramString = JwtUtil.createJWT(map, requestKey);
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("param", paramString);
            //header
            HttpHeaders headers = new HttpHeaders();
            Map<String, Object> headerMap = new HashMap<>();
            headerMap.put("requestId", JwtUtil.getUUID());
            headerMap.put("timestamp", timestamp + "");
        String headerParam = null;
            headerParam = JsonUtil.toJsonStr(headerMap);

        headers.add(LocalConstant.JWT_API_HEADER_PARAM_KEY, headerParam);
            headers.setContentType(MediaType.APPLICATION_JSON);
            log.error("==Header Msg=="+JSON.toJSONString(headers));
            log.error("==paramMap Msg=="+JSON.toJSONString(paramMap));
           //entity
            HttpEntity formEntity = new HttpEntity(paramMap, headers);
            log.error("==formEntity Msg,formEntity:[{}],url:[{}]==", JSON.toJSONString(formEntity), processUrl);
            String resultStr = restTemplate.postForEntity(processUrl,formEntity,String.class).getBody();
            String responseKey = JwtUtil.MD5(uniformJWTKet + timestamp);
            Claims claims = JwtUtil.parseJWT(resultStr, responseKey);
            // 解密客户端返回值
        String results = null;
            results = JsonUtil.toJsonStr(claims);
        log.error("restTemplate.postForEntity result===="+results);
            if(StringUtils.isNotEmpty(results)){
                JSONObject resultJson = JSON.parseObject(results);
                if("0x0".equals(resultJson.get("errorCode"))){
                    result = resultJson.getString("result");
                    return ResultUtil.success(JSON.parseObject(result));
                }else {
                    return ResultUtil.exception(JSON.parseObject(result));
                }
            }

        }catch (IOException e) {
        log.error("msg:{},e:{}",e.getMessage(),e);
        return ResultUtil.exception(e.toString());
         }
        return ResultUtil.exception();
    }

    /**
     *
     * @param user user
     * @return String
     */
    public String getAllAdminUserEmail(LoginUser user){
        StringBuffer emailBuffer =  new StringBuffer();
        emailBuffer.append(user.getEmail());
        List<PageUserVo> listUser = userMapper.adminListUser(user.getId(),"");
        for (PageUserVo userVo:listUser) {
            emailBuffer.append(","+userVo.getEmail());
        }
        return emailBuffer.toString();
    }

    /**
     *
     * @param user user
     * @param email email
     * @return String
     */
    public String getAllAdminUserEmailWithCondition(LoginUser user,String email){
        List<String> userEmailList =  new ArrayList<>();
        userEmailList.add(user.getEmail());
        List<PageUserVo> listUser = userMapper.adminListUser(user.getId(), "");
        for (PageUserVo userVo:listUser) {
            userEmailList.add(userVo.getEmail());
        }
        String [] emailArr = email.split(",");
        List<String> conditionEmailList = Arrays.asList(emailArr);
        if(conditionEmailList.size()>0){
            userEmailList.retainAll(conditionEmailList);
        }
        return JSONObject.toJSONString(userEmailList);
    }
}
